/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.service.TbOfflineShoppingOrderLogServece;
import com.thinkgem.jeesite.modules.sys.service.TbShopProductService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 库存管理Controller
 * @author huoyan403
 * @version 2016-11-09
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/tbShopProduct")
public class TbShopProductController extends BaseController {

	@Autowired
	private TbShopProductService tbShopProductService;

	@Autowired
	private TbOfflineShoppingOrderLogServece tbOffLineShoppingOrderLogServece;
	private  static Map<String,String> map = new HashMap<String,String>();
	@ModelAttribute
	public TbShopProduct get(@RequestParam(required=false) String id) {
		TbShopProduct entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tbShopProductService.get(id);
		}
		if (entity == null){
			entity = new TbShopProduct();
		}
		return entity;
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(TbShopProduct tbShopProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
		String  uid = UserUtils.getUser().getId();
		tbShopProduct.setUid(uid);
		Page<TbShopProduct> page = tbShopProductService.findPage(new Page<TbShopProduct>(request, response), tbShopProduct);
		if(page.getList().size()!=0&&page.getList().get(0).getShopCategoyr()==2){
			model.addAttribute("flag","1");
		}
		model.addAttribute("tbShopProduct", tbShopProduct);
		model.addAttribute("page", page);
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
		return "modules/sys/tbShopProductList";
	}
	@RequestMapping(value = "listpage")
	public String listPage(TbShopProduct tbShopProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
		String  uid = UserUtils.getUser().getId();
		tbShopProduct.setUid(uid);
		Page<TbShopProduct> page = tbShopProductService.findPage(new Page<TbShopProduct>(request, response), tbShopProduct);
		if(page.getList().size()>0){
			if(page.getList().get(0).getReflage().compareTo("2")==0){
				model.addAttribute("overse","1");
			}
		}
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
		model.addAttribute("page", page);
		return "modules/sys/tbShopProductList1";
	}

	@RequestMapping(value = "form")
	public String form(TbShopProduct tbShopProduct, Model model) {
		model.addAttribute("tbShopProduct", tbShopProduct);
		return "modules/sys/tbShopProductForm";
	}

	@RequestMapping(value = "save")
	public String save(TbShopProduct tbShopProduct, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, tbShopProduct)){
			return form(tbShopProduct, model);
		}
		tbShopProductService.update(tbShopProduct);
		addMessage(redirectAttributes, "保存库存管理成功");
		return "redirect:"+Global.getAdminPath()+"/sys/tbShopProduct/?repage";
	}
	
	@RequestMapping(value = "updateStatus")
	public String updateStatus(TbShopProduct tbShopProduct, RedirectAttributes redirectAttributes) {
		tbShopProductService.updateStatus(tbShopProduct);
		addMessage(redirectAttributes, "商品状态修改成功");
		return "redirect:"+Global.getAdminPath()+"/sys/tbShopProduct/listpage/?repage";
	}
	@RequestMapping(value = "delete")
	public String delete(TbShopProduct tbShopProduct, RedirectAttributes redirectAttributes) {
		tbShopProductService.delete(tbShopProduct);
		addMessage(redirectAttributes, "删除库存管理成功");
		return "redirect:"+Global.getAdminPath()+"/sys/tbShopProduct/?repage";
	}

	@RequestMapping("/offlineShopping")
	public String offlineShopping(HttpServletRequest request, HttpServletResponse respons,Model model){
		if(map.size()==0) {
			map.put("1", "支付宝");
			map.put("2", "微信");
			map.put("3", "现金");
			map.put("4", "物业钱包");
			map.put("5", "麻雀钱包");
			map.put("0", "其他");
		}
		model.addAttribute("payWayList",map);
		return "modules/sys/offlineShopping";
	}
	@RequestMapping("/getGoodsInfo")
	public void getGoodsInfo(HttpServletRequest request, HttpServletResponse response, Model model, String goodsNum) throws JSONException, IOException {
		User user = UserUtils.getUser();
		String userId = user.getId();
		JSONArray arr = new JSONArray();
		List<Map<String,Object>> list = tbShopProductService.getProductByBarcode(goodsNum,userId);
		for(int i=0;i<list.size();i++) {
			Map<String,Object> goodsMap = list.get(i);
			JSONObject json = new JSONObject();
			json.put("name", goodsMap.get("title"));
			json.put("color", goodsMap.get("color"));
			json.put("price", goodsMap.get("price"));
			arr.put(json);
		}
		if(null!=arr){
			response.getWriter().print(arr);
		}

	}

	@RequestMapping("/updateGoodlsInfo")
	@ResponseBody
	public String updateGoodlsInfo(HttpServletRequest request, HttpServletResponse response,Model model){
		Map<String,Object> resultMap = new HashMap<String, Object>();
		String alerMessage="";
		User user = UserUtils.getUser();
		String userId = user.getId();
		try {
			String goodsInfoList = request.getParameter("goodsInfoList");
			String payId = request.getParameter("payWay");
			String sumMoney = request.getParameter("sumMoney");
			String paySum = request.getParameter("paySum");
			String giveSum = request.getParameter("giveSum");
			JSONObject json = new JSONObject(goodsInfoList);
			String mobile = request.getParameter("mobile");
			String code = request.getParameter("code");
			resultMap = tbShopProductService.updateProductStoreCount(json,userId,Integer.parseInt(payId),map.get(payId),sumMoney,paySum,mobile,code);
			alerMessage = "结算成功"+(StringUtils.isEmpty(resultMap.get("message").toString())? "":resultMap.get("message"));
			model.addAttribute("paySum",paySum);
			model.addAttribute("giveSum",giveSum);
		}catch(Exception e){
			e.printStackTrace();
			alerMessage = "结算失败"+(StringUtils.isEmpty(e.getMessage())? "":e.getMessage());
		}finally{
			model.addAttribute("payWayList",map);
			model.addAttribute("alerMessage", alerMessage);
		}
		return alerMessage  + (StringUtils.isEmpty(resultMap.get("orderId").toString()) ? "" : ":"+resultMap.get("orderId").toString());
		//return selectoffineShoppingOrderInfo(request, response, model,(Integer)resultMap.get("orderId"));
	}


	@RequestMapping("/offlineShoppingLog")
	public String selectOfflineShoppingLog(TbOfflineShoppingOrderLog orderLog,HttpServletRequest request, HttpServletResponse response,Model model){
		Page<TbOfflineShoppingOrderLog> page = tbOffLineShoppingOrderLogServece.selectOfflineShoppingLog(new Page<TbOfflineShoppingOrderLog>(request, response),orderLog);
		model.addAttribute("orderLogPage",page);
		model.addAttribute("orderLog",orderLog);
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
		model.addAttribute("page", page);
		List tlist=tbOffLineShoppingOrderLogServece.findMoney(orderLog);
		model.addAttribute("zhifubao",tlist.get(0));
		model.addAttribute("weixin",tlist.get(1));
		model.addAttribute("xianjin",tlist.get(2));
		model.addAttribute("wuye",tlist.get(3));
		model.addAttribute("maque",tlist.get(4));
		model.addAttribute("other",tlist.get(5));
		model.addAttribute("maxMoney",tlist.get(6));
		model.addAttribute("remarks",UserUtils.getUser().getRemarks());
		if(null==orderLog||(null!=orderLog&&null==orderLog.getStartTime())){
			Date date=new Date();
			orderLog.setStartTime(date);
			orderLog.setEndTime(date);
		}
		return "modules/sys/offineShoppingOrderLog";
	}
	//结算历史的饼图的的数据读取
	@RequestMapping("/getHistroyPicture")
	public void getHistroyPicture(HttpServletRequest request, HttpServletResponse response, Model model, String goodsNum) throws JSONException, IOException {

		JSONArray arr = new JSONArray();
		/*List tlist=tbOffLineShoppingOrderLogServece.findMoney();

		JSONObject json = new JSONObject();
		json.put("zhifubao", tlist.get(0));
		json.put("weixin", tlist.get(1));
		json.put("xianjin", tlist.get(2));
		json.put("wuye", tlist.get(3));
		json.put("maqu", tlist.get(4));
		json.put("other", tlist.get(5));
		json.put("maxMoney",tlist.get(6));
		arr.put(json);*/

		if(null!=arr){
			response.getWriter().print(arr);
		}

	}
	@RequestMapping("/offineShoppingOrderInfo")
	public String selectoffineShoppingOrderInfo(HttpServletRequest request, HttpServletResponse response,Model model,Integer orderId){
		List<TbOfflineShoppingOrderInfo> list = tbOffLineShoppingOrderLogServece.selectoffineShoppingOrderInfo(orderId);
		model.addAttribute("productList",list);
		model.addAttribute("remarks",UserUtils.getUser().getRemarks());
		return "modules/sys/offineShoppingOrderInfo";
	}

	/**
	 * 导出商品信息
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "exportShopProduct", method= RequestMethod.POST)
	public String exportShopProduct(TbShopProduct tbShopProduct, HttpServletRequest request, HttpServletResponse response, Model model,
									 RedirectAttributes redirectAttributes) {
		try {
			String fileName = "店铺商品信息"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			String  uid = UserUtils.getUser().getId();
			tbShopProduct.setUid(uid);
 			Page<TbShopProduct> page = tbShopProductService.exportProduct(
					new Page<TbShopProduct>(request, response,-1),tbShopProduct);
			new ExportExcel("商品信息", TbShopProduct.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出店铺商品信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/tbShopProduct/list/?repage";
	}
	/**
	 * 导出商品信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "updateProductPriceAjax", method= RequestMethod.POST)
	@ResponseBody
	public String updateProductPriceAjax(Integer id,String price, HttpServletRequest request, HttpServletResponse response) {
		try {
			int count = tbShopProductService.updateProductPriceById(id,price);
			if(count>0)
			return "1";
		} catch (Exception e) {
			logger.info("商品价格修改失败！updateProductPriceAjax，详细："+e.getMessage());
		}
		return "";
	}
	//麻雀钱包充值页面
	@RequestMapping(value = "AddMpWallet")
	public String addMpwallet(TbUser tbUser, RedirectAttributes redirectAttributes,Model model) {
		if(null!=tbUser&&null!=tbUser.getUid()&&!"".equals(tbUser.getUid())){
			//麻雀钱包充值
			tbShopProductService.inserMpWallet(tbUser);
			TbUser tb=tbShopProductService.getTbUserByPhone(tbUser.getMobile());
			tbUser.setAddress(tb.getAddress());
			model.addAttribute("message1","麻雀钱包充值成功");
			addMessage(redirectAttributes, "麻雀钱包充值成功");

		}

		return "modules/sys/addMpWallet";
	}
	//麻雀钱包充值页面
	@RequestMapping(value = "AddTenementWallet")
	public String AddTenementWallet(TbUser tbUser, RedirectAttributes redirectAttributes,Model model) {
		if(null!=tbUser&&null!=tbUser.getUid()&&!"".equals(tbUser.getUid())){
			//麻雀钱包充值
			tbShopProductService.inserTenemetWallet(tbUser);
			TbUser tb=tbShopProductService.getTbUserByPhone(tbUser.getMobile());
			tbUser.setAddress(tb.getAddress());
			model.addAttribute("message1","物业钱包充值成功");
			addMessage(redirectAttributes, "物业钱包充值成功");

		}

		return "modules/sys/addTenementWallet";
	}
	//根据手机号查询出微信端用户的信息
	@RequestMapping("/phoneToNickName")
	public void phoneToNickName(HttpServletRequest request, HttpServletResponse response, Model model, String phone) throws JSONException, IOException {
		TbUser tbUser=tbShopProductService.getTbUserByPhone(phone);
		JSONArray arr = new JSONArray();
		JSONObject json = new JSONObject();
		json.put("uid",tbUser.getUid());
		json.put("nickName",tbUser.getAddress());
		arr.put(json);
		if(null!=arr){
			response.getWriter().print(arr);
		}
	}

}